<template>
  <div class="bg-white overflow-hidden">
    <div class="form-title">企业信息</div>
    <div class="form-container">
      <el-form
        v-loading="formLoading"
        ref="enterpriseForm"
        :model="enterpriseForm"
        label-width="auto"
        :rules="formRules"
      >
        <div>
          <div class="mb-4 text-red-500 text-sm font-bold">* 推荐部门必填</div>
          <el-form-item label="主管部门:" prop="deptId" style="width: 48%">
            <treeselect
              id="deptId"
              v-model="enterpriseForm.deptId"
              :options="deptOptions"
              :show-count="true"
              placeholder="请选择推荐部门"
            />
          </el-form-item>
        </div>

        <div class="form-sub-title">基本信息</div>
        <div
          class="
            w-full
            flex
            justify-between
            content-center
            items-center
            flex-wrap
          "
        >
          <el-form-item
            id="companyName"
            label="企业名称:"
            class="fixed-input-w"
            prop="companyName"
          >
            <el-input v-model="enterpriseForm.companyName"></el-input>
          </el-form-item>

          <el-form-item
            id="creditCode"
            label="统一社会信用代码:"
            class="fixed-input-w"
            prop="creditCode"
          >
            <el-input
              :disabled="true"
              v-model="enterpriseForm.creditCode"
            ></el-input>
          </el-form-item>

          <el-form-item label="注册地址:" class="fixed-input-w" prop="area">
            <el-cascader
              id="area"
              v-model="enterpriseForm.area"
              :options="areaOptions"
              :props="{
                checkStrictly: true,
                value: 'id',
                label: 'name',
                children: 'childern',
              }"
              placeholder="请选择"
              clearable
              style="width: 100%"
              @change="handleChange"
            ></el-cascader>
          </el-form-item>

          <!-- <el-form-item label="注册地址:" class="fixed-input-w" prop="registeredAddress">
            <SelectAddress :regidAddressV="regidAddressV" :provinceValue="regidAddressV.provinceV"
              :cityValue="regidAddressV.cityV" :areaValue="regidAddressV.areaV" @getValue="getRegiAddress" />
          </el-form-item> -->

          <el-form-item label="企业性质:" class="fixed-input-w" prop="nature">
            <el-select
              v-model="enterpriseForm.nature"
              filterable
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in natureOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            id="address"
            label="办公地址:"
            class="fixed-input-w"
            prop="address"
          >
            <el-input v-model="enterpriseForm.address"></el-input>
          </el-form-item>

          <el-form-item
            label="注册资金( 万元 ):"
            class="fixed-input-w"
            prop="registeredMoney"
          >
            <el-input-number
              id="registeredMoney"
              v-model="enterpriseForm.registeredMoney"
              auto-complete="off"
              :controls="false"
              class="m-input-number"
            />
          </el-form-item>

          <el-form-item
            label="实际资金( 万元 ):"
            class="fixed-input-w"
            prop="trueMoney"
          >
            <el-input-number
              id="trueMoney"
              v-model="enterpriseForm.trueMoney"
              auto-complete="off"
              :controls="false"
              class="m-input-number"
            />
          </el-form-item>
        </div>
        <div class="form-sub-title">法人信息</div>
        <div
          class="
            w-full
            flex
            sm:justify-center
            md:justify-between
            content-center
            flex-wrap
            sm:reponsive-form
          "
        >
          <el-form-item
            id="legalPerson"
            label="法人姓名:"
            class="fixed-input-w"
            prop="legalPerson"
          >
            <el-input v-model="enterpriseForm.legalPerson"></el-input>
          </el-form-item>

          <el-form-item
            id="legalPersonCode"
            label="法人身份证号:"
            class="fixed-input-w"
            prop="legalPersonCode"
          >
            <el-input v-model="enterpriseForm.legalPersonCode"></el-input>
          </el-form-item>
          <el-form-item label="国籍:" class="fixed-input-w" prop="nationality">
            <el-select
              v-model="enterpriseForm.nationality"
              placeholder="无"
              style="width: 100%"
              clearable
              filterable
              size="small"
            >
              <el-option
                v-for="(item, index) in nationOptions"
                :key="item.name + index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="国籍:" class="fixed-input-w" prop="nationality"
            ><el-input v-model="enterpriseForm.nationality"></el-input
          ></el-form-item> -->

          <el-form-item
            id="legalPhone"
            label="手机号:"
            class="fixed-input-w"
            prop="legalPhone"
          >
            <el-input v-model="enterpriseForm.legalPhone"></el-input>
          </el-form-item>

          <el-form-item
            id="legalFixedPhone"
            label="联系电话:"
            class="fixed-input-w"
            prop="legalFixedPhone"
          >
            <el-input
              v-model="enterpriseForm.legalFixedPhone"
              placeholder="如: 0791-2943541"
            ></el-input>
          </el-form-item>

          <el-form-item
            id="legalPostCode"
            label="邮政编码:"
            class="fixed-input-w"
            prop="legalPostCode"
          >
            <el-input v-model="enterpriseForm.legalPostCode"></el-input>
          </el-form-item>

          <el-form-item
            id="email"
            label="电子邮箱:"
            class="fixed-input-w"
            prop="email"
          >
            <el-input v-model="enterpriseForm.email"></el-input>
          </el-form-item>
        </div>

        <div class="form-sub-title">股权结构</div>
        <table
          class="self-table-form table-auto border-collapse border"
          style="min-height: auto"
        >
          <tr>
            <td class="m-label text-center w-2/5">股东名称</td>
            <td class="m-label text-center w-2/5" colspan="2">
              持股比例 (所占单位: %)
            </td>
            <td class="m-label text-center w-40">操作</td>
          </tr>

          <tr v-for="(item, index) in enterpriseForm.list" :key="item.id">
            <td>
              <el-form-item
                id="shareholderName"
                label=""
                :prop="'list.' + index + '.name'"
                :rules="[...formRules.shareholderName]"
              >
                <el-input v-model="item.name" placeholder="股东名称"></el-input>
              </el-form-item>
            </td>
            <td colspan="2">
              <el-form-item
                id="shareholderProp"
                :prop="'list.' + index + '.proportion'"
                :rules="[...formRules.shareholderProp]"
              >
                <el-input
                  type="number"
                  v-model.number="item.proportion"
                  placeholder="股东股份"
                ></el-input>
              </el-form-item>
            </td>
            <td>
              <div class="flex justify-center">
                <el-button
                  class="m-auto"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteStockRight(item.id)"
                >
                </el-button>
              </div>
            </td>
          </tr>
          <tr>
            <td :colspan="5">
              <el-button type="primary" @click="addStockRight"
                >添加股东信息</el-button
              >
            </td>
          </tr>
        </table>

        <div class="form-sub-title">其他信息</div>
        <el-row
          :gutter="80"
          type="flex"
          class="w-full mb-4 align-middle justify-around flex-wrap items-center"
        >
          <el-col :span="12">
            <el-form-item label="行业领域:" prop="industryField">
              <el-select
                v-model="enterpriseForm.industryField"
                filterable
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in positionOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="企业规模:" prop="companyScale">
              <el-select
                v-model="enterpriseForm.companyScale"
                filterable
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in scaleOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="企业类别:" prop="companyType">
              <el-select
                v-model="enterpriseForm.companyType"
                filterable
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in enterpriseTypeOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="经营方式:" prop="operationMode">
              <el-select
                v-model="enterpriseForm.operationMode"
                filterable
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in businessTypeOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label-width="4.25rem" prop="isTech">
              <div class="m-label font-bold py-2">是否为高新技术企业</div>
              <el-radio-group
                v-model="enterpriseForm.isTech"
                @change="isTechChange"
              >
                <el-radio :label="1" :value="1"> 是</el-radio>
                <el-radio :label="0" :value="0"> 否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label-width="4.25rem" prop="isWarehousing">
              <div class="m-label font-bold py-2">是否为高新入库培育企业</div>
              <el-radio-group v-model="enterpriseForm.isWarehousing">
                <el-radio :label="1" :value="1"> 是</el-radio>
                <el-radio :label="0" :value="0"> 否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              v-if="techShowMore"
              label="认定时间:"
              prop="cognizanceTime"
            >
              <el-date-picker
                id="cognizanceTime"
                v-model="enterpriseForm.cognizanceTime"
                type="date"
                placeholder="认定时间"
                size="medium"
                style="width: 100%;"
              >
              </el-date-picker>
            </el-form-item>

            <!-- <el-form-item
              id="certificateCode"
              v-if="techShowMore"
              label="证书编码:"
              class="fixed-input-w"
              prop="certificateCode"
            >
              <el-input
                v-model="enterpriseForm.certificateCode"
                size="medium"
              ></el-input>
            </el-form-item> -->
          </el-col>
          <el-col :span="12"></el-col>

          <el-col :span="12"
            ><el-form-item label-width="4.25rem" prop="isBelisted">
              <div class="m-label font-bold py-2">是否有上市计划</div>
              <el-radio-group
                v-model="enterpriseForm.isBelisted"
                @change="isBelistedChange"
              >
                <el-radio :label="1" :value="1"> 是</el-radio>
                <el-radio :label="0" :value="0"> 否</el-radio>
              </el-radio-group>
            </el-form-item></el-col
          >
          <el-col :span="12"></el-col>

          <template v-if="BelistedShowMore">
            <el-col :span="12">
              <el-form-item label="上市时间:" prop="belistedTime">
                <el-date-picker
                  id="belistedTime"
                  v-model="enterpriseForm.belistedTime"
                  type="date"
                  placeholder="上市时间"
                  style="width: 100%;"
                  size="medium"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上市类型:" prop="belistedType">
                <el-select
                  v-model="enterpriseForm.belistedType"
                  filterable
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option disabled>请选择</el-option>
                  <el-option
                    v-for="item in belistedTypeOptions"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="估值( 万元 ):" prop="belistedValuation">
                <el-input-number
                  id="belistedValuation"
                  v-model="enterpriseForm.belistedValuation"
                  auto-complete="off"
                  :controls="false"
                  class="m-input-number"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否新三板挂牌:" prop="isThirdBoard">
                <el-select
                  v-model="enterpriseForm.isThirdBoard"
                  filterable
                  placeholder="请选择"
                  style="width: 100%;"
                >
                  <el-option disabled>请选择</el-option>
                  <el-option label="是" :value="1" />
                  <el-option label="否" :value="0" />
                </el-select>
              </el-form-item>
            </el-col>
          </template>

          <el-col :span="12"
            ><el-form-item label-width="4.25rem" prop="isFinancing">
              <div class="m-label font-bold py-2">是否有融资需求</div>
              <el-radio-group v-model="enterpriseForm.isFinancing">
                <el-radio :label="1" :value="1"> 是</el-radio>
                <el-radio :label="0" :value="0"> 否</el-radio>
              </el-radio-group>
            </el-form-item></el-col
          >

          <el-col :span="12"
            ><el-form-item label-width="4.25rem" prop="isLoan">
              <div class="m-label font-bold py-2">是否有贷款需求</div>
              <el-radio-group v-model="enterpriseForm.isLoan">
                <el-radio :label="1" :value="1"> 是</el-radio>
                <el-radio :label="0" :value="0"> 否</el-radio>
              </el-radio-group>
            </el-form-item></el-col
          >

          <el-col :span="12"
            ><el-form-item label-width="4.25rem" prop="isInvestment">
              <div class="m-label font-bold py-2">是否有投资需求</div>
              <el-radio-group v-model="enterpriseForm.isInvestment">
                <el-radio :label="1" :value="1"> 是</el-radio>
                <el-radio :label="0" :value="0"> 否</el-radio>
              </el-radio-group>
            </el-form-item></el-col
          >
          <el-col :span="12"></el-col>
        </el-row>

        <el-form-item label-width="0.5rem" prop="introduction">
          <div class="m-label font-bold py-2">企业简介（限 400 字以内）</div>
          <el-input
            type="textarea"
            maxlength="400"
            :autosize="{ minRows: 3 }"
            show-word-limit
            v-model="enterpriseForm.introduction"
          ></el-input>
        </el-form-item>

        <el-form-item label-width="0.5rem" prop="remark">
          <div class="m-label font-bold py-2">经营范围（限 400 字以内）</div>
          <el-input
            type="textarea"
            maxlength="400"
            :autosize="{ minRows: 3 }"
            show-word-limit
            v-model="enterpriseForm.remark"
          ></el-input>
        </el-form-item>

        <el-form-item label-width="0.5rem" prop="comProblems">
          <div class="m-label font-bold py-2">
            企业遇到的问题及希望政府支持的事项（限 400 字以内）
          </div>
          <el-input
            type="textarea"
            maxlength="400"
            :autosize="{ minRows: 3 }"
            show-word-limit
            v-model="enterpriseForm.comProblems"
          ></el-input>
        </el-form-item>

        <table
          class="self-table-form table-auto border-collapse ml-2 border"
          style="min-height: auto"
        >
          <tr>
            <td class="m-label text-center w-1/5">产品或服务名称</td>
            <td class="m-label text-center w-1/5">主要用途</td>
            <td class="m-label text-center w-1/5">年销售额(万元)</td>
            <td class="m-label text-center w-1/5">毛利率/税后净利率</td>
            <td class="m-label text-center w-40">操作</td>
          </tr>

          <tr
            v-for="(item, index) in enterpriseForm.productList"
            :key="item.id"
          >
            <td>
              <el-form-item
                id="productName"
                label=""
                :prop="'productList.' + index + '.name'"
                :rules="formRules.productName"
              >
                <el-input
                  v-model="item.name"
                  placeholder="产品或服务名称"
                ></el-input>
              </el-form-item>
            </td>
            <td>
              <el-form-item
                id="productRemark"
                :prop="'productList.' + index + '.remark'"
                :rules="formRules.productRemark"
              >
                <el-input
                  v-model="item.remark"
                  placeholder="主要用途"
                ></el-input>
              </el-form-item>
            </td>
            <td>
              <el-form-item
                id="productMoney"
                :prop="'productList.' + index + '.money'"
                :rules="formRules.productMoney"
              >
                <el-input
                  type="number"
                  v-model.number="item.money"
                  placeholder="年销售额(万元)"
                ></el-input>
              </el-form-item>
            </td>
            <td>
              <el-form-item
                id="interestRate"
                :prop="'productList.' + index + '.interestRate'"
                :rules="formRules.productInterestRate"
              >
                <el-input
                  type="number"
                  step="0.01"
                  v-model.number="item.interestRate"
                  placeholder="毛利率/税后净利率"
                >
                </el-input>
              </el-form-item>
            </td>

            <td>
              <div class="flex justify-center">
                <el-button
                  class="m-auto"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteProduct(item.id)"
                >
                </el-button>
              </div>
            </td>
          </tr>
          <tr>
            <td :colspan="5">
              <el-button type="primary" @click="addProductItem">添加</el-button>
            </td>
          </tr>
        </table>

        <el-form-item id="mainCost" label-width=".5rem" prop="mainCost">
          <div class="m-label font-bold py-2">
            主要成本构成（限 400 字以内）
          </div>
          <el-input
            type="textarea"
            maxlength="400"
            :autosize="{ minRows: 3 }"
            show-word-limit
            v-model="enterpriseForm.mainCost"
          ></el-input>
        </el-form-item>

        <el-form-item id="profitModel" label-width=".5rem" prop="profitModel">
          <div class="m-label font-bold py-2">盈利模式（限 400 字以内）</div>
          <el-input
            type="textarea"
            maxlength="400"
            :autosize="{ minRows: 3 }"
            show-word-limit
            v-model="enterpriseForm.profitModel"
          ></el-input>
        </el-form-item>

        <el-form-item
          id="competitiveEdge"
          label-width=".5rem"
          prop="competitiveEdge"
        >
          <div class="m-label font-bold py-2">
            企业主要竞争优势（限 400 字以内）
          </div>
          <el-input
            type="textarea"
            maxlength="400"
            :autosize="{ minRows: 3 }"
            show-word-limit
            v-model="enterpriseForm.competitiveEdge"
          ></el-input>
        </el-form-item>

        <el-form-item id="mainFactor" label-width=".5rem" prop="mainFactor">
          <div class="m-label font-bold py-2">
            影响公司业务发展的主要因素（限 400 字以内）
          </div>
          <el-input
            type="textarea"
            maxlength="400"
            :autosize="{ minRows: 3 }"
            show-word-limit
            v-model="enterpriseForm.mainFactor"
          ></el-input>
        </el-form-item>

        <div class="flex justify-between py-10 text-center">
          <el-button
            v-if="isSubmit"
            class="confirm-btn tracking-widest"
            type="primary"
            size="medium"
            @click="submitForm"
            >保存 / 下一步</el-button
          >
          <DeclareNextItem ref="next" v-show="false" />
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import {
  checNumber,
  limitLength,
  limitLengthFocus,
  requiredInput,
} from "@/utils/formRules.js";
import SelectAddress from "@/components/SelectAddress";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

import { treeselects } from "@/api/system/dept";
import { saveCompanyInfo } from "@/api/declareForm/company";
import {
  getCompanyInfo,
  updateCompanyInfo,
} from "@/api/manageInformation/baseInfo";
import { getSpecificArea } from "@/api/system/user";
import { queryNationList } from "@/api/";

export default {
  name: "EnterpriseInfoForm",
  props: {
    sourceList: {
      type: Object,
      default: {},
    },
    isSubmit: {
      type: Boolean,
      default: false,
    },
  },
  components: {
    Treeselect,
    SelectAddress,
  },
  data() {
    var checkCreditCode = (rule, value, callback) => {
      if (!value) {
        // return callback(new Error("统一社会信用代码不能为空"));
        return callback();
      }
      let reg = /[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}/;
      if (!reg.test(value)) {
        callback(new Error("请输入有效统一社会信用代码"));
      } else {
        callback();
      }
    };
    // 检验身份证号 省份码
    var checkProv = function (val) {
      var pattern = /^[1-9][0-9]/;
      var provs = {
        11: "北京",
        12: "天津",
        13: "河北",
        14: "山西",
        15: "内蒙古",
        21: "辽宁",
        22: "吉林",
        23: "黑龙江 ",
        31: "上海",
        32: "江苏",
        33: "浙江",
        34: "安徽",
        35: "福建",
        36: "江西",
        37: "山东",
        41: "河南",
        42: "湖北 ",
        43: "湖南",
        44: "广东",
        45: "广西",
        46: "海南",
        50: "重庆",
        51: "四川",
        52: "贵州",
        53: "云南",
        54: "西藏 ",
        61: "陕西",
        62: "甘肃",
        63: "青海",
        64: "宁夏",
        65: "新疆",
        71: "中国台湾",
        81: "中国香港",
        82: "中国澳门",
      };
      if (pattern.test(val)) {
        if (provs[val]) {
          return true;
        }
      }
      return false;
    };
    // 检验身份证号 日期码
    var checkDate = function (val) {
      var pattern =
        /^(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)$/;
      if (pattern.test(val)) {
        var year = val.substring(0, 4);
        var month = val.substring(4, 6);
        var date = val.substring(6, 8);
        var date2 = new Date(year + "-" + month + "-" + date);
        if (date2 && date2.getMonth() == parseInt(month) - 1) {
          return true;
        }
      }
      return false;
    };
    // 检验身份证号 校检码
    var checkCode = function (val) {
      var p =
        /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
      var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
      var parity = [1, 0, "X", 9, 8, 7, 6, 5, 4, 3, 2];
      var code = val.substring(17);
      if (p.test(val)) {
        var sum = 0;
        for (var i = 0; i < 17; i++) {
          sum += val[i] * factor[i];
        }
        if (parity[sum % 11] == code.toUpperCase()) {
          return true;
        }
      }
      return false;
    };
    // 检验身份证号
    var checkID = (rule, value, callback) => {
      if (!value) {
        // return callback(new Error("身份证号不能为空"));
        return callback();
      }
      if (checkCode(value)) {
        var date = value.substring(6, 14);
        if (checkDate(date)) {
          if (checkProv(value.substring(0, 2))) {
            return callback();
          }
        }
      }
      document.getElementById("legalPersonCode").querySelector("input").focus();
      return callback(new Error("请输入有效身份证号"));
    };

    // 校验手机号
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback();
      }
      let reg = /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
      if (!reg.test(value)) {
        document.getElementById("legalPhone").querySelector("input").focus();
        callback(new Error("请输入有效手机号"));
      } else {
        callback();
      }
    };

    // 校验联系电话（座机号）
    var checkTelephone = (rule, value, callback) => {
      if (!value) {
        return callback();
      }
      let reg = /^(0\d{2,3}-\d{7,8})$/;

      if (!reg.test(value)) {
        document
          .getElementById("legalFixedPhone")
          .querySelector("input")
          .focus();
        callback(new Error("请输入有效联系电话"));
      } else {
        callback();
      }
    };

    // 校验邮箱
    var checkMail = (rule, value, callback) => {
      if (!value) {
        return callback();
      }
      let reg = /^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/;
      if (!reg.test(value)) {
        document.getElementById("email").querySelector("input").focus();
        callback(new Error("请输入有效邮箱格式"));
      } else {
        callback();
      }
    };
    // 校验邮政编码
    var checkPostCode = (rule, value, callback) => {
      if (!value) {
        return callback();
      }
      let reg = /[1-9]\d{5}(?!\d)/;
      if (!reg.test(value)) {
        document.getElementById("legalPostCode").querySelector("input").focus();
        callback(new Error("请输入有效邮政编码"));
      } else {
        callback();
      }
    };

    var checkProportion = (rule, value, callback) => {
      if (!value || value > 100 || value < 0) {
        document
          .getElementById("shareholderProp")
          .querySelector("input")
          .focus();
        return callback(new Error("请输入有效值"));
      }
      let nowProption = 0;
      this.enterpriseForm.list.forEach((item) => {
        nowProption += Number(item.proportion);
      });
      if (nowProption > 100) {
        document
          .getElementById("shareholderProp")
          .querySelector("input")
          .focus();
        return callback(new Error("所填比例 大于 剩余比例"));
      } else {
        return callback();
      }
    };

    return {
      formLoading: false,

      // 显隐是否为高新技术企业
      techShowMore: false,
      // 显隐是否有上市计划
      BelistedShowMore: false,

      regidAddressV: {
        provinceV: "",
        cityV: "",
        areaV: "",
      },
      area: [],
      // 省市区选项
      areaOptions: [],

      // 国籍列表
      nationOptions: [],

      enterpriseForm: {
        deptId: undefined,

        companyName: "",
        creditCode: "",
        registeredAddress: "",
        registeredProvinceId: "",
        registeredCityId: "",
        registeredAreaId: "",
        area: [],

        cognizanceTime: undefined,
        certificateCode: undefined,

        nature: "",
        address: "",
        registeredMoney: "",
        trueMoney: "",

        legalPerson: "",
        legalPersonCode: "",
        nationality: "",
        legalPhone: "",
        legalFixedPhone: "",
        legalPostCode: "",
        email: "",
        list: [],
        productList: [],

        industryField: "",
        companyScale: "",
        companyType: "",
        operationMode: "",

        isTech: 0,
        isWarehousing: 0,
        isBelisted: 0,
        belistedTime: undefined,
        belistedType: undefined,
        belistedValuation: 0,
        isThirdBoard: 0,
        isFinancing: 0,
        isLoan: 0,
        isInvestment: 0,

        remark: "",
        introduction: "",
        /**主要成本构成*/
        mainCost: "",
        /**盈利模式*/
        profitModel: "",
        /** 企业遇到的问题及希望政府支持的事项 */
        comProblems: "",
        /**企业主要竞争优势*/
        competitiveEdge: "",
        /**影响公司业务发展的主要因素*/
        mainFactor: "",
        relationId: "",
      },

      formRules: {
        deptId: [
          {
            required: true,
            validator: requiredInput("推荐部门为必填项", "deptId"),
            trigger: "change",
          },
        ],
        companyName: [
          {
            required: true,
            validator: requiredInput("请输入企业名称", "companyName"),
            trigger: "blur",
          },
          {
            validator: limitLengthFocus(
              50,
              "企业名称不能超过50个字符, 请删减后重试",
              "companyName"
            ),
            trigger: "blur",
          },
        ],
        creditCode: [
          {
            required: true,
            validator: requiredInput("请输入社会统一信用代码", "creditCode"),
            trigger: "blur",
          },
          {
            validator: limitLengthFocus(
              20,
              "社会统一信用代码不能超过20个字符, 请删减后重试",
              "creditCode"
            ),
            trigger: "blur",
          },
          // { validator: checkCreditCode, trigger: "blur" }
        ],
        area: [
          {
            type: "array",
            required: true,
            validator: requiredInput("注册地址为必填项", "area"),
          },
        ],
        cognizanceTime: [
          // {
          //   required: true,
          //   message: "请选择认定时间",
          //   trigger: "blur"
          // }
        ],
        certificateCode: [
          // {
          //   required: true,
          //   message: "请输入证书编码",
          //   trigger: "blur"
          // }
          {
            validator: limitLengthFocus(
              30,
              "证书编码不能超过30个字符, 请删减后重试",
              "certificateCode"
            ),
            trigger: "blur",
          },
        ],
        registeredAddress: [
          // { required: true, message: "请输入注册地址", trigger: "blur" }
        ],
        nature: [
          // { required: true, message: "请选择企业性质", trigger: "blur" }
        ],
        address: [
          // { required: true, message: "请输入办公地址", trigger: "blur" }
          {
            validator: limitLengthFocus(
              50,
              "办公地址不能超过50个字符, 请删减后重试",
              "address"
            ),
            trigger: "blur",
          },
        ],
        registeredMoney: [
          // { required: true, message: "请输入注册资金", trigger: "blur" },
          {
            validator: limitLengthFocus(
              12,
              "注册资金不能超过12个字符, 请删减后重试",
              "registeredMoney"
            ),
            trigger: "blur",
          },
          { validator: checNumber, trigger: "blur" },
        ],
        trueMoney: [
          // { required: true, message: "请输入实际资金", trigger: "blur" }

          {
            validator: limitLengthFocus(
              12,
              "实际资金不能超过12个字符, 请删减后重试",
              "trueMoney"
            ),
            trigger: "blur",
          },
          { validator: checNumber, trigger: "blur" },
        ],
        legalPerson: [
          // { required: true, message: "请输入法人姓名", trigger: "blur" }
          {
            validator: limitLengthFocus(
              10,
              "法人姓名不能超过12个字符, 请删减后重试",
              "legalPerson"
            ),
            trigger: "blur",
          },
        ],
        legalPersonCode: [
          // { required: true, message: "请输入身份证号", trigger: "blur" },
          {
            validator: limitLengthFocus(
              30,
              "身份证号不能超过30个字符, 请删减后重试",
              "legalPersonCode"
            ),
            trigger: "blur",
          },
          { validator: checkID, trigger: "blur" },
        ],
        nation: [
          // { required: true, message: "请输入国籍", trigger: "blur" }
        ],
        legalPhone: [
          // { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkPhone, trigger: "blur" },
        ],
        legalFixedPhone: [
          {
            validator: limitLengthFocus(
              20,
              "联系电话不能超过20个字符, 请删减后重试",
              "legalFixedPhone"
            ),
            trigger: "blur",
          },
          { validator: checkTelephone, trigger: "blur" },
          // { required: true, message: "请输入联系电话", trigger: "blur" }
        ],
        legalPostCode: [
          {
            validator: limitLengthFocus(
              6,
              "邮政编码不能超过6个字符, 请删减后重试",
              "legalPostCode"
            ),
            trigger: "blur",
          },
          // { required: true, message: "请输入邮政编码", trigger: "blur" },
          { validator: checkPostCode, trigger: "blur" },
        ],
        email: [
          {
            validator: limitLengthFocus(
              50,
              "电子邮箱不能超过50个字符, 请删减后重试",
              "email"
            ),
            trigger: "blur",
          },
          // { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkMail, trigger: "blur" },
        ],
        // ----- 股权结构 -----------
        // 股东名称
        shareholderName: [
          {
            required: true,
            validator: requiredInput("请输入股东名称", "shareholderName"),
            trigger: "blur",
          },
          {
            validator: limitLengthFocus(
              20,
              "股东名称不能超过20个字符, 请删减后重试",
              "shareholderName"
            ),
            trigger: "blur",
          },
        ],
        // 股东股份
        shareholderProp: [
          {
            validator: limitLengthFocus(
              20,
              "持股比例不能超过20个字符, 请删减后重试",
              "shareholderProp"
            ),
            trigger: "blur",
          },
          {
            validator: checkProportion,
            trigger: "blur",
          },
        ],

        // -------------产品服务
        productName: [
          {
            required: true,
            validator: requiredInput("请输入名称", "productName"),
            trigger: "blur",
          },
          {
            validator: limitLengthFocus(
              20,
              "名称不能超过20个字符, 请删减后重试",
              "productName"
            ),
            trigger: "blur",
          },
        ],
        productRemark: [
          {
            required: true,
            validator: requiredInput("请输入主要用途", "productRemark"),
            trigger: "blur",
          },
          {
            validator: limitLengthFocus(
              20,
              "主要用途不能超过20个字符, 请删减后重试",
              "productRemark"
            ),
            trigger: "blur",
          },
        ],
        productMoney: [
          {
            required: true,
            validator: requiredInput("请输入年销售额（万元）", "productMoney"),
            trigger: "blur",
          },
          {
            validator: limitLengthFocus(
              15,
              "年销售额不能超过15个字符, 请删减后重试",
              "productMoney"
            ),
            trigger: "blur",
          },
        ],
        productInterestRate: [
          {
            required: true,
            validator: requiredInput(
              "请输入毛利率/税后净利率",
              "productInterestRate"
            ),
            trigger: "blur",
          },
          {
            validator: limitLengthFocus(
              10,
              "毛利率/税后净利率不能超过10个字符, 请删减后重试",
              "productInterestRate"
            ),
            trigger: "blur",
          },
        ],

        type: [
          // { required: true, message: "请选择行业领域", trigger: "blur" }
        ],
        companyScale: [
          // { required: true, message: "请选择企业规模", trigger: "blur" }
        ],
        companyType: [
          // { required: true, message: "请选择企业类别", trigger: "blur" }
        ],
        operationMode: [
          // { required: true, message: "请选择经营方式", trigger: "blur" }
        ],
        remark: [
          {
            validator: limitLength(400),
            trigger: "blur",
          },
          // { required: true, message: "请输入经营范围", trigger: "blur" }w
        ],
        introduction: [
          {
            validator: limitLength(400),
            trigger: "blur",
          },
          // { required: true, message: "请输入企业简介", trigger: "blur" }
        ],
        mainCost: [
          {
            validator: limitLength(400),
            trigger: "blur",
          },
          // { required: true, message: "请输入主要成本构成", trigger: "blur" }
        ],
        profitModel: [
          {
            validator: limitLength(400),
            trigger: "blur",
          },
          // { required: true, message: "请输入盈利模式", trigger: "blur" }
        ],
        competitiveEdge: [
          {
            validator: limitLength(400),
            trigger: "blur",
          },
          // { required: true, message: "请输入企业主要竞争优势", trigger: "blur" }
        ],
        mainFactor: [
          {
            validator: limitLength(400),
            trigger: "blur",
          },
          // { required: true, message: "请输入影响公司业务发展的主要因素", trigger: "blur" }
        ],
      },

      // 部门树选项
      deptOptions: [],
      // 行业领域类别
      positionOptions: [],
      // 公司规模类别
      scaleOptions: [],
      // 企业类别
      enterpriseTypeOptions: [],
      // 企业性质
      natureOptions: [],
      // 经营方式
      businessTypeOptions: [],
      // 上市类型
      belistedTypeOptions: [],

      // 字典列表
      dictNameList: [
        "declare_enterprise_natrue",
        "declare_enterprise_type",
        "declare_enterprise_scale",
        "declare_position_type",
        "declare_bussiness_type",
        "belisted_type",
      ],
    };
  },
  watch: {
    sourceList: {
      handler(v, oldv) {
        // console.log("企业信息");
        // console.log(v);
        this.coverCompanyInfo(v);
        // if (v) {
        //   this.enterpriseForm = v;
        //   this.enterpriseForm["list"] = v.stockRightList;
        //   this.enterpriseForm["industryField"] = String(v.industryField);
        //   this.enterpriseForm["companyScale"] = String(v.companyScale);
        //   this.enterpriseForm["companyType"] = String(v.companyType);
        //   this.enterpriseForm["operationMode"] = String(v.operationMode);
        //   this.enterpriseForm["nature"] =
        //     v.nature || v.nature == 0 ? String(v.nature) : "";
        //   this.initRegiAddress(
        //     v.registeredProvinceId,
        //     v.registeredCityId,
        //     v.registeredAreaId
        //   );
        // } else {
        //   this.getCompanyInfoFun();
        // }
      },
      immediate: true,
    },
    "enterpriseForm.isTech": {
      handler(v, oldv) {
        this.isTechChange(v);
      },
      immediate: true,
    },
    "enterpriseForm.isBelisted": {
      handler(v, oldv) {
        this.isBelistedChange(v);
      },
      immediate: true,
    },
  },
  created() {
    // 获取部门下拉树
    this.getTreeselect();
    this.initRelationId();
    this.initDictList();
    this.getSpecificAreaFun();
    this.initNationTypeList();
  },
  mounted() {},
  methods: {
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselects().then((response) => {
        this.deptOptions = response.data;
      });
    },

    // 初始化 国籍列表
    initNationTypeList() {
      queryNationList().then((res) => {
        if (res.data) {
          let tempArr = res.data.map((item) => {
            item.id = String(item.id);
            return item;
          });
          this.nationOptions = tempArr;

          if (!this.enterpriseForm.nationality) {
            this.enterpriseForm.nationality = tempArr[0].id;
          }
        }
      });
    },

    // 初始化所有字典类别
    initDictList() {
      // 加载
      this.formLoading = true;

      this.getDicts(this.dictNameList[0]).then((res) => {
        if (res.code == 200) {
          this.natureOptions = res.data;
        }
      });
      this.getDicts(this.dictNameList[1]).then((res) => {
        if (res.code == 200) {
          this.enterpriseTypeOptions = res.data;
        }
      });
      this.getDicts(this.dictNameList[2]).then((res) => {
        if (res.code == 200) {
          this.scaleOptions = res.data;
        }
      });
      this.getDicts(this.dictNameList[3]).then((res) => {
        if (res.code == 200) {
          this.positionOptions = res.data;
        }
      });
      this.getDicts(this.dictNameList[4]).then((res) => {
        if (res.code == 200) {
          this.businessTypeOptions = res.data;
        }
      });
      this.getDicts(this.dictNameList[5]).then((res) => {
        if (res.code == 200) {
          this.belistedTypeOptions = res.data;
        }
      });

      setTimeout(() => {
        this.$nextTick(() => {
          this.formLoading = false;
        });
      }, 500);
    },

    // 是否为高新技术企业 选择
    isTechChange(e) {
      if (e) {
        this.techShowMore = true;
      } else {
        this.techShowMore = false;
      }
    },
    // 是否有上市计划 选择
    isBelistedChange(e) {
      if (e) {
        this.BelistedShowMore = true;
      } else {
        this.BelistedShowMore = false;
      }
    },

    coverCompanyInfo(sourceV) {
      let v = "";
      if (sourceV) {
        v = JSON.parse(JSON.stringify(sourceV));
      }
      if (v.creditCode || this.sourceList.creditCode) {
        // if (!v) {
        //   v = JSON.parse(JSON.stringify(this.sourceList));
        // }
        for (const key in this.enterpriseForm) {
          if (
            Object.hasOwnProperty.call(this.enterpriseForm, key) &&
            Object.hasOwnProperty.call(v, key) &&
            v[key]
          ) {
            this.enterpriseForm[key] = v[key];
          }
        }
        // this.enterpriseForm = v;
        this.enterpriseForm["list"] = v.stockRightList;
        // this.enterpriseForm["productList"] = v.productList;
        this.enterpriseForm["nationality"] = v.nationality
          ? String(v.nationality)
          : "";
        this.enterpriseForm["industryField"] = v.industryField
          ? String(v.industryField)
          : "";
        this.enterpriseForm["companyScale"] = v.companyScale
          ? String(v.companyScale)
          : "";
        this.enterpriseForm["companyType"] = v.companyType
          ? String(v.companyType)
          : "";
        this.enterpriseForm["operationMode"] = v.operationMode
          ? String(v.operationMode)
          : "";
        this.enterpriseForm["nature"] =
          v.nature || v.nature == 0 ? String(v.nature) : "";

        // 回显注册地址
        this.initRegiAddress(
          v.registeredProvinceId,
          v.registeredCityId,
          v.registeredAreaId
        );

        // 回显主管部门
        this.enterpriseForm.deptId = v.deptId;
      } else {
        this.getCompanyInfoFun();
      }
    },
    getCompanyInfoFun() {
      this.companyManagerId = this.$store.state.user.companyId;

      if (this.companyManagerId) {
        getCompanyInfo(this.companyManagerId).then((res) => {
          if (res.code == 200 && !this.enterpriseForm.creditCode) {
            // this.companyInfo = res.data;
            this.enterpriseForm = Object.assign(
              {},
              this.enterpriseForm,
              res.data
            );

            this.enterpriseForm.companyName = res.data.companyName;
            this.enterpriseForm.creditCode = res.data.creditCode;
            this.enterpriseForm.nature = res.data.nature;
            this.enterpriseForm.address = res.data.address;

            // 还原注册地址
            if (this.enterpriseForm.declareAddress) {
              // 将返回的数组重新转换为number类型 防止数据无法还原
              // this.area = this.enterpriseForm.declareAddress
              //   .split(",")
              //   .map(Number);
              let areaList = this.enterpriseForm.declareAddress
                ? this.enterpriseForm.declareAddress.split(",")
                : [];

              this.initRegiAddress(
                Number(areaList[0]),
                Number(areaList[1]),
                Number(areaList[2])
              );
            }

            this.enterpriseForm.legalPerson = res.data.legalPerson;
            this.enterpriseForm.legalPersonCode = res.data.legalPersonCode;
            this.enterpriseForm.nationality = res.data.nationality
              ? String(res.data.nationality)
              : "";
            this.enterpriseForm.legalPhone = res.data.legalPhone;
            this.enterpriseForm.legalFixedPhone = res.data.legalFixedPhone;
            this.enterpriseForm.legalPostCode = res.data.legalPostCode;
            this.enterpriseForm.email = res.data.email;
            this.enterpriseForm.registeredMoney =
              res.data.registeredMoney || undefined;
            this.enterpriseForm.trueMoney = res.data.trueMoney || undefined;

            // 从缓存内获取deptId还原至推荐部门内
            this.enterpriseForm.deptId = this.$store.getters.deptId;
            // this.enterpriseForm.remark = res.data.mainBusiness;
            // this.enterpriseForm.introduction = res.data.introduction;
          }
        });
      }
    },
    /* 查询江西省省市区信息 */
    getSpecificAreaFun() {
      getSpecificArea().then((res) => {
        this.areaOptions = [res.data];
      });
    },
    handleChange(value) {
      // this.form.address = value.join(',');
      // this.form.areaGrade = value.length - 1;
      // let [last] = [...value].reverse();
      // this.form.area = last;
    },
    initRelationId() {
      let realationId = this.$route.query.id;
      if (realationId || realationId == 0) {
        this.enterpriseForm.relationId = parseInt(realationId);
      }
    },

    addStockRight() {
      let timeChuo = new Date();
      let addObj = { id: timeChuo.valueOf(), name: "", proportion: "" };
      this.enterpriseForm.list.push(addObj);
      this.$forceUpdate();
    },

    addProductItem() {
      let timeChuo = new Date();
      let addObj = {
        id: timeChuo.valueOf(),
        name: "",
        money: "",
        interestRate: "",
        remark: "",
      };
      this.enterpriseForm.productList.push(addObj);

      this.$forceUpdate();
    },
    /**
     * @function deleteStockRight
     * @description 删除表单 股东人 选项
     */
    deleteStockRight(id) {
      let tempArr = JSON.parse(JSON.stringify(this.enterpriseForm.list));
      let newArr = tempArr.filter((item) => {
        return item.id !== id;
      });
      this.enterpriseForm.list = newArr;
    },
    /**
     * @function deleteProduct
     * @description 删除 主要产品或服务 选项
     */
    deleteProduct(id) {
      let tempArr = JSON.parse(JSON.stringify(this.enterpriseForm.productList));
      let newArr = tempArr.filter((item) => {
        return item.id !== id;
      });
      this.enterpriseForm.productList = newArr;
    },

    /** 不清楚是否继续保留 */
    checkProportion(rule, value, callback) {
      if (!value || value > 100 || value < 0) {
        this.$message({
          showClose: true,
          type: "error",
          message: "持股比例输入非法！请输入0-100之间的数字",
          duration: 0,
        });
        return callback(new Error("请输入有效值"));
      }
      let nowProption = 0;
      this.enterpriseForm.list.forEach((item) => {
        nowProption += Number(item.proportion);
      });
      if (nowProption > 100) {
        this.$message({
          showClose: true,
          type: "error",
          message: "持股比例输入非法！所填比例 大于 剩余比例",
          duration: 0,
        });
        return callback(new Error("所填比例 大于 剩余比例"));
      } else {
        return callback();
      }
    },

    /**
     * @function handlePropInput
     * @param id [number]: 股东信息数组 唯一key id
     *        index [nubmer]: 股东信息数组 索引
     * @description 表单项股东持有股份 输入
     */
    handlePropInput(id, index) {
      let canMaxProption = 0;
      this.enterpriseForm.list.forEach((item) => {
        if (item.id !== id) {
          canMaxProption += Number(item.proportion);
        }
      });

      canMaxProption = 100 - canMaxProption < 0 ? 0 : 100 - canMaxProption;
      let inputV = this.enterpriseForm.list[index]["proportion"];
      if (isNaN(Number(inputV))) {
        this.enterpriseForm.list[index]["proportion"] = 0;
      }
      if (inputV < 0) {
        this.enterpriseForm.list[index]["proportion"] = 0;
      }
      if (inputV > canMaxProption) {
        this.$message({
          type: "error",
          message: "所填比例 大于 剩余比例",
        });
        this.enterpriseForm.list[index]["proportion"] = 0;
      }
    },

    getRegiAddress(finalAddress) {
      let addressStr = JSON.stringify(finalAddress);
      this.enterpriseForm.registeredAddress = addressStr;
    },

    initRegiAddress(ProvinceId, CityId, AreaId) {
      this.enterpriseForm.area = [];
      // 如果任何一级出现了空值，则后续联动不成立 直接返回当前值
      if (ProvinceId) {
        this.enterpriseForm.area.push(ProvinceId);
        if (CityId) {
          this.enterpriseForm.area.push(CityId);
          if (AreaId) {
            this.enterpriseForm.area.push(AreaId);
          }
        }
      }
    },

    initSourceList() {
      if (sourceList) {
        this.enterpriseForm = sourceList;
      }
    },

    arrangeRegistAddress(area) {
      if (area) {
        return {
          registeredProvinceId: area[0],
          registeredCityId: area[1],
          registeredAreaId: area[2],
        };
      }
      return {
        registeredProvinceId: "",
        registeredCityId: "",
        registeredAreaId: "",
      };
    },
    nextDeclareItem() {
      let id = parseInt(this.$route.query.id);
      let typeId = parseInt(this.$route.query.typeId);
      let declareIndex = parseInt(this.$route.query.declareIndex);
      if ((id || id == 0) && (typeId || typeId == 0) && declareIndex > -1) {
        this.$router.replace({
          path: "/enterprise/form",
          query: { id, typeId, declareIndex: declareIndex + 1 },
        });
      }
    },

    /**
     * @function submitForm
     * @descrtion 表单提交
     *
     */
    async submitForm() {
      let formName = "enterpriseForm";
      this.enterpriseForm.registeredMoney =
        this.enterpriseForm.registeredMoney || 0;
      this.enterpriseForm.trueMoney = this.enterpriseForm.trueMoney || 0;
      // let addressInfo = this.$refs["selectAddress"].getAddress();
      // this.enterpriseForm.registeredAddress = this.regi;
      return new Promise((resolve, reject) => {
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            this.formLoading = true;
            this.enterpriseForm["relationId"] = this.$route.query.id;
            let addressR = this.arrangeRegistAddress(this.enterpriseForm.area);
            for (const key in addressR) {
              if (Object.hasOwnProperty.call(addressR, key)) {
                const element = addressR[key];
                this.enterpriseForm[key] = element;
              }
            }
            this.enterpriseForm.nationality = Number(
              this.enterpriseForm.nationality
            );
            if (!this.enterpriseForm.isTech) {
              this.enterpriseForm.certificateCode = undefined;
              this.enterpriseForm.cognizanceTime = undefined;
            }

            let { area, ...obj } = this.enterpriseForm;
            let res = await saveCompanyInfo(obj);

            this.formLoading = false;

            if (res && res.code === 200) {
              // console.log("-----res----------");
              // console.log(res);
              this.$message({
                type: "success",
                message: "企业信息保存成功",
              });

              // 跳转至下一页
              this.$refs.next.nextDeclareItem();
              resolve(true);
            } else {
              resolve(false);
            }

            this.enterpriseForm.nationality = String(
              this.enterpriseForm.nationality
            );
          } else {
            // this.msgError(res.msg);
            this.formLoading = false;
            resolve(false);
          }
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.fixed-input-w {
  width: 48%;
}

/** 通用inputNumber样式 */
.m-input-number {
  width: 100%;

  ::v-deep .el-input__inner {
    text-align: left;
  }
}
</style>
